package com.woniuxy.controller;

import com.woniuxy.entity.UploadResult;
import com.woniuxy.util.ResponseData;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/oss")
public class OssController {

    @Value("${minio.bucketName}")
    private String bucketName;

    private final MinioClient minioClient;

    @Autowired
    public OssController(MinioClient minioClient) {
        this.minioClient = minioClient;
    }

    @PostMapping("/upload")
    public ResponseData<UploadResult> upload(@RequestParam("file") MultipartFile file) {
        return ResponseData.ok(uploadFile(file, bucketName));
    }

    // 启动时初始化桶
    @PostConstruct
    public void initBucket() {
        try {
            // 检查存储桶是否存在，不存在则创建
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
        } catch (Exception e) {
            throw new RuntimeException("初始化桶失败：" + e.getMessage(), e);
        }
    }

    // 通用的文件上传方法
    private UploadResult uploadFile(MultipartFile file, String bucketName) {
        String originalFileName = file.getOriginalFilename();

        // 生成文件名，包含时间戳
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String timestamp = LocalDateTime.now().format(formatter);
        String fileName = "ZX" + timestamp + "_" + originalFileName;

        long size = file.getSize();

        try (InputStream inputStream = file.getInputStream()) {
            // 上传文件
            ObjectWriteResponse oss = minioClient.putObject(
                    PutObjectArgs.builder()
                            .stream(inputStream, size, -1L)
                            .object(fileName)
                            .bucket(bucketName)
                            .build()
            );

            // 获取文件访问URL
            String url = minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(bucketName)
                            .object(fileName)
                            .build());

            return new UploadResult(oss.object(), url);
        } catch (MinioException | IOException | InvalidKeyException | NoSuchAlgorithmException e) {
            // 细化异常类型（根据实际引入的异常类调整）
            throw new RuntimeException("文件上传失败: " + e.getMessage(), e);
        }
    }

}
